import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter/services.dart';
import 'package:mobile_vpn/common/ext/asset_ext.dart';
import 'dart:async';
import 'package:slider_captcha/slider_captcha.dart';

import '../../../common/cpn/sliver_app_bar.dart'; // 图形验证码组件

class SetPasswordPage extends StatefulWidget {
  const SetPasswordPage({Key? key}) : super(key: key);

  @override
  _SetPasswordPageState createState() => _SetPasswordPageState();
}

class _SetPasswordPageState extends State<SetPasswordPage> {
  // 验证相关状态
  final TextEditingController _codeController = TextEditingController();
  final TextEditingController _newPwdController = TextEditingController();
  final TextEditingController _confirmPwdController = TextEditingController();
  bool _showCaptcha = false; // 图形验证码弹窗显示状态
  bool _isCountingDown = false;
  int _countdown = 60;
  String _codeError = '';

  // 获取当前用户手机号（实际项目从状态管理获取）
  String get _userPhone =>
      '138****${DateTime.now().second.toString().padLeft(2, '0')}';

  @override
  void dispose() {
    _codeController.dispose();
    _newPwdController.dispose();
    _confirmPwdController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        children: [
          _buildMainContent(),
          if (_showCaptcha) _buildCaptchaOverlay(),
        ],
      ),
    );
  }

  // 主内容区域
  Widget _buildMainContent() {
    return CustomScrollView(
      slivers: [
        commonSliverAppBar(
          title: '修改密码',
        ),
        SliverToBoxAdapter(
          child: Padding(
            padding: EdgeInsets.all(24.w),
            child: Column(
              children: [
                _buildVerificationField(),
                SizedBox(height: 40.h),
                _buildPasswordField(
                  controller: _newPwdController,
                  label: '新密码',
                  hint: '8-20位字母数字组合',
                ),
                SizedBox(height: 30.h),
                _buildPasswordField(
                  controller: _confirmPwdController,
                  label: '确认密码',
                  hint: '请再次输入新密码',
                ),
                SizedBox(height: 60.h),
                _buildSubmitButton(),
              ],
            ),
          ),
        ),
      ],
    );
  }

  // 验证码输入区域
  Widget _buildVerificationField() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text('验证码',
                style: TextStyle(fontSize: 28.sp, color: Colors.grey[600])),
            TextButton(
              onPressed: _isCountingDown ? null : _showCaptchaDialog,
              child: Text(
                _isCountingDown ? '${_countdown}s后重试' : '获取验证码',
                style: TextStyle(
                  fontSize: 26.sp,
                  color: _isCountingDown ? Colors.grey : Colors.blue,
                ),
              ),
            ),
          ],
        ),
        SizedBox(height: 12.h),
        TextField(
          controller: _codeController,
          keyboardType: TextInputType.number,
          inputFormatters: [FilteringTextInputFormatter.digitsOnly],
          decoration: InputDecoration(
            hintText: '请输入6位验证码',
            errorText: _codeError.isEmpty ? null : _codeError,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
              borderSide: BorderSide.none,
            ),
            filled: true,
            fillColor: Colors.grey[100],
            contentPadding:
                EdgeInsets.symmetric(horizontal: 20.w, vertical: 18.h),
          ),
          onChanged: (v) => setState(() => _codeError = _validateCode(v)),
        ),
      ],
    );
  }

  // 密码输入字段通用组件
  Widget _buildPasswordField({
    required TextEditingController controller,
    required String label,
    String? hint,
  }) {
    final obscureText =
        controller == _newPwdController ? _obscureNewPwd : _obscureConfirmPwd;
    final toggle = () => setState(() {
          if (controller == _newPwdController) {
            _obscureNewPwd = !_obscureNewPwd;
          } else {
            _obscureConfirmPwd = !_obscureConfirmPwd;
          }
        });

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: TextStyle(fontSize: 28.sp, color: Colors.grey[600])),
        SizedBox(height: 12.h),
        TextField(
          controller: controller,
          obscureText: obscureText,
          decoration: InputDecoration(
            hintText: hint,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
              borderSide: BorderSide.none,
            ),
            filled: true,
            fillColor: Colors.grey[100],
            contentPadding:
                EdgeInsets.symmetric(horizontal: 20.w, vertical: 18.h),
            suffixIcon: IconButton(
              icon: Icon(obscureText ? Icons.visibility_off : Icons.visibility),
              onPressed: toggle,
            ),
          ),
        ),
      ],
    );
  }

  // 提交按钮
  Widget _buildSubmitButton() {
    return SizedBox(
      width: double.infinity,
      height: 80.h,
      child: ElevatedButton(
        onPressed: _submitChange,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.blue[700],
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.r),
          ),
        ),
        child: Text(
          '确认修改',
          style: TextStyle(fontSize: 32.sp, color: Colors.white),
        ),
      ),
    );
  }

  // 图形验证码弹窗
  Widget _buildCaptchaOverlay() {
    return GestureDetector(
      onTap: () => setState(() => _showCaptcha = false),
      child: Container(
        color: Colors.black54,
        child: Center(
          child: Container(
            width: MediaQuery.of(context).size.width * 0.8,
            padding: EdgeInsets.all(24.w),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16.r),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text('安全验证',
                    style: TextStyle(
                        fontSize: 32.sp, fontWeight: FontWeight.bold)),
                SizedBox(height: 16.h),
                Text('拖动滑块完成拼图验证',
                    style: TextStyle(fontSize: 26.sp, color: Colors.grey)),
                SizedBox(height: 32.h),
                SliderCaptcha(
                  image: Image.asset('toutiao'.jpeg,),
                  colorBar: Colors.blue,
                  colorCaptChar: Colors.blue,
                  title: '向右滑动完成验证',
                  onConfirm: (success) {
                    setState(() => _showCaptcha = false);
                    if (success) {
                      _sendVerificationCode();
                    } else {
                      Get.snackbar(' 验证失败', '请重新滑动拼图');
                    }
                    return Future.value(success);
                  },
                ),
                SizedBox(height: 24.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    TextButton(
                      onPressed: () => setState(() => _showCaptcha = false),
                      child: Text('取消', style: TextStyle(fontSize: 26.sp)),
                    ),
                    SizedBox(width: 20.w),
                    TextButton(
                      onPressed: () => setState(() {}), // 刷新验证码
                      child: Text('刷新',
                          style:
                              TextStyle(fontSize: 26.sp, color: Colors.blue)),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 显示图形验证码弹窗
  void _showCaptchaDialog() {
    setState(() => _showCaptcha = true);
  }

  // 发送验证码（验证通过后调用）
  void _sendVerificationCode() {
    setState(() {
      _isCountingDown = true;
      _showCaptcha = false;
    });

    // 启动倒计时
    Timer.periodic(Duration(seconds: 1), (timer) {
      if (_countdown == 0) {
        timer.cancel();
        setState(() {
          _isCountingDown = false;
          _countdown = 60;
        });
      } else {
        setState(() => _countdown--);
      }
    });

    Get.snackbar(' 验证码已发送', '已向 $_userPhone 发送短信验证码');
  }

  // 验证码格式校验
  String _validateCode(String code) {
    if (code.isEmpty) return '请输入验证码';
    if (!RegExp(r'^\d{6}$').hasMatch(code)) return '验证码必须为6位数字';
    return '';
  }

  // 提交修改
  void _submitChange() {
    // 验证验证码
    final codeError = _validateCode(_codeController.text);
    if (codeError.isNotEmpty) {
      setState(() => _codeError = codeError);
      return;
    }

    // 验证密码
    if (_newPwdController.text.length < 8) {
      Get.snackbar(' 密码太短', '密码长度不能少于8位');
      return;
    }

    if (_newPwdController.text != _confirmPwdController.text) {
      Get.snackbar(' 密码不一致', '两次输入的密码不相同');
      return;
    }

    // 实际项目调用修改密码接口
    Get.snackbar(' 修改成功', '密码已更新', snackPosition: SnackPosition.BOTTOM);
    Future.delayed(Duration(seconds: 1), () => Navigator.pop(context));
  }

  // 密码可见性状态
  bool _obscureNewPwd = true;
  bool _obscureConfirmPwd = true;
}
